package ws.very.translator

import scala.util.Try
import org.json4s.JArray
import org.json4s.JString
import org.json4s.JValue
import org.json4s.jvalue2extractable
import org.json4s.native.JsonMethods.parse
import org.json4s.string2JsonInput
import dispatch.as
import dispatch.enrichFuture
import dispatch.implyRequestHandlerTuple
import dispatch.url
import dispatch.Http

case class GoogleTrans(implicit executor: scala.concurrent.ExecutionContext, http: Http) {
  def translate(txt: S, fromLang: S = "auto")(implicit toLang: S) = new {
    val resStr = http(
      url(
        s"http://translate.google.com/translate_a/t?client=t&sl=${fromLang}&tl=${toLang}&ie=UTF-8&oe=UTF-8&multires=1&oc=2&otf=1&ssel=4&tsel=4&pc=1&sc=1" //&q=${txt}
        ).addQueryParameter("q", txt) OK as.String).either
    lazy val fixRes = resStr.right.map { _.replaceAll(",+", ",") }

    lazy val parseJson = fixRes.right.map { r => Try { parse(r) } }

    lazy val json2Obj = (parseJson).right.map { _.map { a => extract(a(0)) -> a(1).extract[S] } } // 

    def extract(j: JValue) =
      j match {
        case JArray(a) =>
          a.map {
            case JArray(aa) =>
              aa.map {
                case JString(a) =>
                  a
              }
          }
      }
    lazy val rs = json2Obj.right.map { _.map { case (s, lang) => s.map { _.head }.mkString -> lang } }

  }
}